//
//  UIImagePickerController+Block.m
//  JQKit
//
//  Created by JQZ on 2017/12/29.
//  Copyright © 2017年 JQZ. All rights reserved.
//

#import "UIImagePickerController+Block.h"
#import <objc/runtime.h>

char * const JQImagePickerFinishingBlock = "JQImagePickerFinishingBlock";
char * const JQImagePickerCancelingBlock = "JQImagePickerCancelingBlock";

@implementation UIImagePickerController (Block)

- (id)initWithSourceType:(UIImagePickerControllerSourceType)source didFinishPickingHandle:(UIImagePickerDidFinishPickingHandle)didFinishPickingHandle didCancelHandle:(UIImagePickerDidCancelHandle)didCancelHandle
{
    self = [self init];
    if (self)
    {
        [self setDidFinishPickingHandle:didFinishPickingHandle];
        [self setDidCancelHandle:didCancelHandle];
        [self setSourceType:source];
        [self setDelegate:self];
    }
    return  self;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if (self.didFinishPickingHandle){
        self.didFinishPickingHandle(picker, info, ((UIImage *)[info objectForKey:UIImagePickerControllerOriginalImage]), ((UIImage *)[info objectForKey:UIImagePickerControllerEditedImage]));
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    if (self.didCancelHandle){
        self.didCancelHandle(picker);
    }
}

- (void)setDidFinishPickingHandle:(UIImagePickerDidFinishPickingHandle)actionBlock
{
    objc_setAssociatedObject(self, JQImagePickerFinishingBlock, actionBlock, OBJC_ASSOCIATION_COPY);
}

- (UIImagePickerDidFinishPickingHandle)didFinishPickingHandle
{
    return objc_getAssociatedObject(self, JQImagePickerFinishingBlock);
}

- (void)setDidCancelHandle:(UIImagePickerDidCancelHandle)actionBlock
{
    objc_setAssociatedObject(self, JQImagePickerCancelingBlock, actionBlock, OBJC_ASSOCIATION_COPY);
}

- (UIImagePickerDidCancelHandle)didCancelHandle
{
    return objc_getAssociatedObject(self, JQImagePickerCancelingBlock);
}

@end
